package com.labot.i18n;

import java.util.List;
import java.util.ListResourceBundle;
import java.util.Locale;

import org.springframework.stereotype.Component;

import com.labot.model.I18n;
import com.labot.webapp.listener.StartupListener;

@Component
public abstract class CustomListResourceBundle extends ListResourceBundle {

	/**
	 * Cache! Use reloadBoundles to reload to sync db with cache!
	 */
	private static Object[][] resources    = null;
	private static Object[][] resources_es = null;
	
    public CustomListResourceBundle() {
    }
    
    /**
     * Setup keys
     */
    public static void reloadBoundles() {
    	List<I18n> lista = StartupListener.getI18Manager().getAll();
    	resources = new Object[lista.size()][2];
    	resources_es = new Object[lista.size()][2];
    	ListResourceBundle.clearCache();
    	int i = 0;
    	for (I18n i18n : lista) {
			resources[i][0] = i18n.getKey();
			resources[i][1] = i18n.getEn();
			resources_es[i][0] = i18n.getKey();
			resources_es[i][1] = i18n.getEs();
			i++;
		}
    }
    
    protected Object[][] getContents(Locale locale) {
    	if(locale.getCountry().toLowerCase().startsWith("en")) {
    		if (resources == null) {
    			reloadBoundles();
    		}
    		return resources;
    	} else if(locale.getCountry().toLowerCase().startsWith("es")) {
    		if (resources_es == null) {
    			reloadBoundles();
    		}
    		return resources_es;
    	}
    	return null;
    }
    
}